package com.bio.socket;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Arrays;

/**
 * Created by fangjicai on 2020/6/4.
 */
public class SocketClinet {
    public static void main(String[] args) throws IOException {
        String fileName = "E:\\test\\Natasha.zip";
        BufferedInputStream fileInputStream = new BufferedInputStream(new FileInputStream(fileName));
        byte[] buff = new byte[8192];
        String fileLength = String.valueOf(fileInputStream.available());
        byte[] fileLengthByte = Arrays.copyOf(fileLength.getBytes(), 15);
        byte[] fileNameLengthByte = Arrays.copyOf(String.valueOf(fileName.length()).getBytes(), 2);
        Socket socket = new Socket("127.0.0.1", 8009);
        BufferedOutputStream socketOutputStream = new BufferedOutputStream(socket.getOutputStream());
        socketOutputStream.write(fileLengthByte);
        socketOutputStream.write(fileNameLengthByte);
        socketOutputStream.write(fileName.getBytes());
        socketOutputStream.flush();
        int read = fileInputStream.read(buff);
        while (read != -1) {
            socketOutputStream.write(buff, 0, read);
            read = fileInputStream.read(buff);
        }
        fileInputStream.close();
        socketOutputStream.flush();
        System.out.println("文件发送完毕！");
        socket.shutdownInput();
        socket.shutdownOutput();
        socket.close();
    }
}
